package com.tenement.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tenement.entity.Chat;
import com.tenement.entity.ChatModel;
import com.tenement.mapper.ChatMapper;
import com.tenement.service.ChatService;
import com.tenement.service.UserService;
import com.tenement.vo.QueryVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.tenement.entity.table.ChatTableDef.CHAT;
import static com.tenement.entity.table.UserTableDef.USER;

/**
 *  服务层实现。
 *
 * @author BertXie
 * @since 1.0.1
 */
@Service
@RequiredArgsConstructor
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements ChatService {

    private final ChatMapper chatMapper;

    private final UserService userService;

    @Override
    public int offLine(List<Long> sentUser, ChatModel chat) {
        List<Long> noSentUser = userService.listAs(QueryWrapper.create().from(USER)
                .select(USER.ID)
                .where(USER.ID.notIn(sentUser)), Long.class);
        if (CollectionUtil.isNotEmpty(noSentUser)) {
            List<Chat> chats = noSentUser.stream().map(
                    userId -> new Chat()
                            .setTarget(userId)
                            .setStatus((short) 0)
                            .setType(chat.getType())
                            .setSendTime(chat.getSendTime())
                            .setMsg(chat.getMsg())
            ).collect(Collectors.toList());
            return chatMapper.insertBatch(chats);
        }
        return 0;
    }

    @Override
    public Page<Chat> list(QueryVo queryVo) {
        QueryWrapper queryWrapper = QueryWrapper.create().from(CHAT)
                .where(
                        CHAT.MSG.like(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord()))
                                .or(USER.NAME.like(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord())))
                )
                .leftJoin(USER).on(CHAT.USER_ID.eq(USER.ID))
                .leftJoin(USER).on(USER.ID.eq(CHAT.TARGET))
                .and(CHAT.STATUS.eq(queryVo.getStatus()));
        return chatMapper.paginate(queryVo.getPage(),queryVo.getSize(),queryWrapper);
    }

    @Override
    public int removeByUser(Long userId, Long targetId) {
        return chatMapper.deleteByQuery(QueryWrapper.create().from(CHAT).where(CHAT.USER_ID.eq(userId).and(CHAT.TARGET.eq(targetId))));
    }

    @Override
    public long noReadCount(Long userId) {
        QueryWrapper queryWrapper = QueryWrapper.create().from(CHAT).where(CHAT.TARGET.eq(userId).and(CHAT.STATUS.eq((short) 0)));
        return chatMapper.selectCountByQuery(queryWrapper);
    }


}
